<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="导演姓名">
        <el-select v-model="searchFrom.name"
                   clearable
                   filterable
                   style="width:220px;"
                   placeholder="请输入导演名字">
          <el-option
              v-for="item in tableData"
              :label="item.name"
              :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="国籍">
        <el-select v-model="searchFrom.nationality"
                   clearable
                   filterable
                   style="width:220px;"
                   placeholder="请选择国籍">
          <el-option
              v-for="item in nationalityList"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin:20px;">
    <div style="margin:10px 0 40px 10px;">
      导演列表
      <el-button type="success" style="float: right;margin-top:-3px;" @click="addDirector">新增导演</el-button>
    </div>
    <el-table :data="paginatedData"
              style="height: 465px">>
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column prop="name" label="导演姓名" align="center"/>
      <el-table-column prop="nationality" label="国籍" align="center"
                       :formatter="nationalityFormatter"/>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary"
                     @click="editDirector(scope.row.id)">编辑
          </el-button>
          <el-button link type="danger"
                     @click="deleteDirector(scope.row.id)">删除
          </el-button>
          <el-button link type="primary"
                     @click="findAll(scope.row.id)">详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />

  </el-card>


  <el-dialog :title="directorTitle"
             v-model="directorVisible"
             style="width:800px; padding:40px;"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="导演姓名">
            <el-input placeholder="请输入导演姓名"
                      v-model="saveFrom.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国籍">
            <el-select v-model="saveFrom.nationality"
                       clearable
                       filterable
                       placeholder="请选择国籍">
              <el-option
                  v-for="item in nationalityList"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="导演简介">
            <el-input
                v-model="saveFrom.intro"
                :autosize="{ minRows: 6, maxRows: 4 }"
                maxlength="200"
                show-word-limit
                type="textarea"
                placeholder="请输入相关信息"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="导演照片">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img :src="dialogImageUrl"
                   :alt="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <el-button type="danger" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveDirector">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="particularsVisible" style="width: 800px;
                                                 position: absolute;
                                                 top: 30%;left: 40%;
                                                 transform: translate(-20%, -50%);
                                                 padding: 20px">
    <el-descriptions title="详情信息"
                     border
                     label-width="80px">
      <el-descriptions-item
          :rowspan="1"
          :width="140"
          label="导演图片"
          align="center"
      >
        <el-image
            v-if="particularsData && particularsData.poster"
            style="width: 100px; height: auto"
            :src="BASE_URL + particularsData.poster"
            alt="User Avatar"
        />
      </el-descriptions-item>
      <el-descriptions-item label="导演姓名" align="center">{{ particularsData.name }}</el-descriptions-item>
      <el-descriptions-item label="导演国籍" align="center">
        {{ nationalityFormatter(particularsData, null, particularsData.nationality) }}
      </el-descriptions-item>
      <el-descriptions-item label="导演简介" align="left">{{ particularsData.intro }}</el-descriptions-item>


    </el-descriptions>
  </el-dialog>

</template>


<script setup>
import {computed, onMounted, ref} from "vue";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";

const nationalityList = ref([]);
onMounted(() => {
  loadDictOptions(nationalityList, 'nationality');
});
console.log(nationalityList)
const nationalityFormatter = (row, column, cellValue, index) => {
  if (!nationalityList.value) {
    return cellValue;
  }
  for (let item of nationalityList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchFrom = ref({
  name: '',
  nationality: '',
  intro: '',
});
const search = () => {
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/director/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  search();
})
const resetSearch = () => {
  searchFrom.value = {};
  search();
}
const directorVisible = ref(false);
const directorTitle = ref('新增导演');
const saveFrom = ref({
  name: '',
  nationality: '',
  intro: '',
  poster: '',
});
const cleanAll = () => {
  saveFrom.value = {
    name: '',
    nationality: '',
    intro: '',
    poster: '',
  };
  fileList.value = [];
}
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/
const addDirector = () => {
  directorVisible.value = true;
  directorTitle.value = '新增导演';
}

const saveDirector = () => {
  if (saveFrom.value.name === null || saveFrom.value.name === '') {
    errorInfo('请输入导演姓名');
    return;
  }
  if (saveFrom.value.nationality === null || saveFrom.value.nationality === '') {
    errorInfo('请选择导演国籍');
    return;
  }
  if (saveFrom.value.intro === null || saveFrom.value.intro === '') {
    errorInfo('请输入导演简介');
    return;
  }
  if (fileList.value.length === 0) {
    errorInfo('请上传导演照片');
    return;
  }
  saveFrom.value.poster = fileList.value[0].response.data;
  let data = qs.stringify(saveFrom.value);
  axios.post(BASE_URL + '/v1/director/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          directorVisible.value = false;
          cleanAll();
          search();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })


}
const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    cleanAll();
    directorVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}

const editDirector = (id) => {
  directorVisible.value = true;
  directorTitle.value = '编辑导演';
  axios.get(BASE_URL + '/v1/director/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveFrom.value = response.data.data[0];
          fileList.value = [{
            url: BASE_URL + saveFrom.value.poster,
            response: {
              data: saveFrom.value.poster
            }
          }]
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}
const deleteDirector = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/director/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
      Info('已取消删除')
    });
}

const particularsVisible = ref(false);
const particularsData = ref({
  name: '',
  nationality: '',
  intro: '',
  poster: '',
  createTime: '',
});
const findAll = (id) => {
  particularsVisible.value = true;
  axios.get(BASE_URL + '/v1/director/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          particularsData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
</script>

<style scoped>

</style>